import { useEffect } from 'react';
import { Form, Modal } from 'antd';
import { componentsMap } from '@/utils/util';

function ChangePassword({ visible, onCancel, onCreate }) {
  const [form] = Form.useForm();

  const validatePass = async (rule, value) => {
    if (!value) {
      return Promise.reject('请再次输入新密码');
    } else if (value !== form.getFieldValue('password')) {
      return Promise.reject('两次输入的新密码不一致');
    } else {
      return Promise.resolve();
    }
  };
  useEffect(() => {
    if (visible) {
      form.resetFields();
    }
  }, [visible]);
  const formList = [
    {
      name: 'oldPwd',
      title: '旧密码',
      type: 'input',
      otherProps: {
        type: 'password',
      },
      rules: [
        {
          required: true,
          message: '请输入旧密码',
        },
      ],
    },
    {
      name: 'password',
      title: '新密码',
      type: 'input',
      otherProps: {
        type: 'password',
      },
      rules: [
        {
          required: true,
          message: '请输入新密码',
        },
      ],
    },
    {
      name: 'checkPass',
      title: '确认新密码',
      type: 'input',
      otherProps: {
        type: 'password',
      },
      rules: [
        {
          required: true,
          validator: validatePass,
        },
      ],
    },
  ];
  return (
    <Modal
      visible={visible}
      title="修改密码"
      okText="确定"
      cancelText="取消"
      onCancel={onCancel}
      maskClosable={false}
      destroyOnClose
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form form={form} className="changePwd">
        {formList.map((item) => {
          return (
            <Form.Item
              key={item.name}
              label={item.title}
              name={item.name}
              rules={item.rules}
            >
              {componentsMap(item.type, item.otherProps)}
            </Form.Item>
          );
        })}
      </Form>
    </Modal>
  );
}

export default ChangePassword;
